import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader } from '../components/UI/Card';
import { Badge } from '../components/UI/Badge';
import { Button } from '../components/UI/Button';
import { Modal } from '../components/UI/Modal';
import { ToastContainer } from '../components/UI/Toast';
import { Pagination } from '../components/UI/Pagination';
import { useToast } from '../hooks/useToast';
import { mockApi } from '../services/mockApi';
import { Financial } from '../types';
import { 
  DollarSign,
  TrendingUp,
  TrendingDown,
  Plus,
  Filter,
  Search,
  Download,
  FileText,
  Calendar,
  PieChart,
  Save,
  X,
  Receipt,
  CreditCard,
  Banknote,
  Wallet,
  RotateCcw,
  ChevronDown,
  ChevronUp,
  Smartphone,
  Building2
} from 'lucide-react';
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  LineChart,
  Line,
  PieChart as RechartsPieChart,
  Pie,
  Cell
} from 'recharts';

const mockFinanceChartData = [
  { month: '1月', income: 850000, expense: 620000 },
  { month: '2月', income: 780000, expense: 580000 },
  { month: '3月', income: 920000, expense: 680000 },
  { month: '4月', income: 1100000, expense: 750000 },
  { month: '5月', income: 980000, expense: 690000 },
  { month: '6月', income: 1250000, expense: 820000 },
];

const expenseCategories = [
  { name: '燃油费', value: 35, color: '#ef4444' },
  { name: '过路费', value: 25, color: '#f97316' },
  { name: '维修费', value: 20, color: '#eab308' },
  { name: '工资', value: 15, color: '#22c55e' },
  { name: '其他', value: 5, color: '#6366f1' },
];

interface FinancialForm {
  type: 'income' | 'expense';
  category: string;
  amount: number;
  description: string;
  date: string;
  paymentMethod: string;
  orderId?: string;
  vehicleId?: string;
  invoiceNumber?: string;
}

interface DateRange {
  start: string;
  end: string;
}

interface AdvancedFilters {
  dateRange: DateRange;
  amountRange: {
    min: string;
    max: string;
  };
  categories: string[];
  paymentMethods: string[];
  status: string;
}

// 支付方式图标映射
const getPaymentMethodIcon = (method: string) => {
  const iconMap: { [key: string]: React.ReactNode } = {
    '现金': <Banknote className="w-4 h-4" />,
    '银行转账': <Building2 className="w-4 h-4" />,
    '支付宝': <Smartphone className="w-4 h-4" />,
    '微信支付': <Smartphone className="w-4 h-4" />,
    '信用卡': <CreditCard className="w-4 h-4" />,
    '支票': <Receipt className="w-4 h-4" />,
    '其他': <Wallet className="w-4 h-4" />
  };
  return iconMap[method] || <Wallet className="w-4 h-4" />;
};

// 支付方式颜色映射
const getPaymentMethodColor = (method: string) => {
  const colorMap: { [key: string]: string } = {
    '现金': 'text-green-600 bg-green-100',
    '银行转账': 'text-blue-600 bg-blue-100',
    '支付宝': 'text-blue-500 bg-blue-50',
    '微信支付': 'text-green-500 bg-green-50',
    '信用卡': 'text-purple-600 bg-purple-100',
    '支票': 'text-orange-600 bg-orange-100',
    '其他': 'text-gray-600 bg-gray-100'
  };
  return colorMap[method] || 'text-gray-600 bg-gray-100';
};

export const Finance: React.FC = () => {
  const [financials, setFinancials] = useState<Financial[]>([]);
  const [loading, setLoading] = useState(true);
  const [typeFilter, setTypeFilter] = useState<string>('');
  const [searchTerm, setSearchTerm] = useState('');
  const [currentPage, setCurrentPage] = useState(1);
  const [totalFinancials, setTotalFinancials] = useState(0);
  
  // 新增财务记录相关状态
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [createLoading, setCreateLoading] = useState(false);
  const [exportLoading, setExportLoading] = useState(false);
  const [financialForm, setFinancialForm] = useState<FinancialForm>({
    type: 'income',
    category: '',
    amount: 0,
    description: '',
    date: new Date().toISOString().split('T')[0],
    paymentMethod: '现金',
    orderId: '',
    vehicleId: '',
    invoiceNumber: ''
  });

  // 日期和筛选相关状态
  const [dateRange, setDateRange] = useState<DateRange>({
    start: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0], // 30天前
    end: new Date().toISOString().split('T')[0] // 今天
  });
  const [showAdvancedFilter, setShowAdvancedFilter] = useState(false);
  const [advancedFilters, setAdvancedFilters] = useState<AdvancedFilters>({
    dateRange: {
      start: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
      end: new Date().toISOString().split('T')[0]
    },
    amountRange: { min: '', max: '' },
    categories: [],
    paymentMethods: [],
    status: ''
  });
  const [activeFiltersCount, setActiveFiltersCount] = useState(0);

  const { toasts, removeToast, success, error, warning, info } = useToast();

  const pageSize = 10;

  // 收入和支出分类选项
  const incomeCategories = [
    '运费收入',
    '仓储费',
    '包装费',
    '保险费',
    '增值服务费',
    '其他收入'
  ];

  const expenseCategories_list = [
    '燃油费',
    '过路费',
    '维修费',
    '工资',
    '保险费',
    '车辆折旧',
    '办公费用',
    '其他支出'
  ];

  // 支付方式选项
  const paymentMethods = [
    '现金',
    '银行转账',
    '支付宝',
    '微信支付',
    '信用卡',
    '支票',
    '其他'
  ];

  // 状态选项
  const statusOptions = [
    { value: 'completed', label: '已完成' },
    { value: 'pending', label: '待处理' },
    { value: 'cancelled', label: '已取消' }
  ];

  useEffect(() => {
    fetchFinancials();
  }, [currentPage, typeFilter, dateRange]);

  // 计算活跃筛选器数量
  useEffect(() => {
    let count = 0;
    if (advancedFilters.amountRange.min || advancedFilters.amountRange.max) count++;
    if (advancedFilters.categories.length > 0) count++;
    if (advancedFilters.paymentMethods.length > 0) count++;
    if (advancedFilters.status) count++;
    setActiveFiltersCount(count);
  }, [advancedFilters]);

  const fetchFinancials = async () => {
    setLoading(true);
    try {
      const { data, total } = await mockApi.getFinancials({
        type: typeFilter || undefined,
        page: currentPage,
        limit: pageSize,
      });
      setFinancials(data);
      setTotalFinancials(total);
    } catch (error) {
      console.error('Failed to fetch financials:', error);
    } finally {
      setLoading(false);
    }
  };

  // 应用所有筛选条件
  const filteredFinancials = financials.filter(financial => {
    // 基础搜索筛选
    const matchesSearch = financial.description.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         financial.category.toLowerCase().includes(searchTerm.toLowerCase());

    if (!matchesSearch) return false;

    // 日期范围筛选
    const financialDate = new Date(financial.date);
    const startDate = new Date(dateRange.start);
    const endDate = new Date(dateRange.end);
    
    if (financialDate < startDate || financialDate > endDate) return false;

    // 金额范围筛选
    if (advancedFilters.amountRange.min && financial.amount < parseInt(advancedFilters.amountRange.min)) return false;
    if (advancedFilters.amountRange.max && financial.amount > parseInt(advancedFilters.amountRange.max)) return false;

    // 分类筛选
    if (advancedFilters.categories.length > 0 && !advancedFilters.categories.includes(financial.category)) return false;

    // 支付方式筛选
    if (advancedFilters.paymentMethods.length > 0 && financial.paymentMethod && !advancedFilters.paymentMethods.includes(financial.paymentMethod)) return false;

    // 状态筛选
    if (advancedFilters.status && financial.status !== advancedFilters.status) return false;

    return true;
  });

  // Calculate stats based on filtered data
  const totalIncome = filteredFinancials.filter(f => f.type === 'income').reduce((sum, f) => sum + f.amount, 0);
  const totalExpense = filteredFinancials.filter(f => f.type === 'expense').reduce((sum, f) => sum + f.amount, 0);
  const profit = totalIncome - totalExpense;
  const profitMargin = totalIncome > 0 ? ((profit / totalIncome) * 100).toFixed(1) : '0';

  const totalPages = Math.ceil(totalFinancials / pageSize);

  // 处理日期范围变化
  const handleDateRangeChange = (field: 'start' | 'end', value: string) => {
    const newDateRange = { ...dateRange, [field]: value };
    setDateRange(newDateRange);
    setAdvancedFilters(prev => ({
      ...prev,
      dateRange: newDateRange
    }));
  };

  // 处理高级筛选变化
  const handleAdvancedFilterChange = (key: keyof AdvancedFilters, value: any) => {
    setAdvancedFilters(prev => ({
      ...prev,
      [key]: value
    }));
  };

  // 处理分类选择
  const handleCategoryToggle = (category: string) => {
    setAdvancedFilters(prev => ({
      ...prev,
      categories: prev.categories.includes(category)
        ? prev.categories.filter(c => c !== category)
        : [...prev.categories, category]
    }));
  };

  // 处理支付方式选择
  const handlePaymentMethodToggle = (method: string) => {
    setAdvancedFilters(prev => ({
      ...prev,
      paymentMethods: prev.paymentMethods.includes(method)
        ? prev.paymentMethods.filter(m => m !== method)
        : [...prev.paymentMethods, method]
    }));
  };

  // 重置筛选条件 - 移除提示信息
  const resetFilters = () => {
    const defaultDateRange = {
      start: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
      end: new Date().toISOString().split('T')[0]
    };
    
    setDateRange(defaultDateRange);
    setAdvancedFilters({
      dateRange: defaultDateRange,
      amountRange: { min: '', max: '' },
      categories: [],
      paymentMethods: [],
      status: ''
    });
    setTypeFilter('');
    setSearchTerm('');
    // 移除了提示信息，重置筛选是常规操作，不需要提示
  };

  // 应用筛选 - 移除提示信息
  const applyFilters = () => {
    setShowAdvancedFilter(false);
    // 移除了提示信息，应用筛选也是常规操作
  };

  // 处理创建财务记录
  const handleCreateFinancial = async () => {
    // 表单验证
    if (!financialForm.category) {
      error('验证失败', '请选择财务分类');
      return;
    }
    if (!financialForm.description.trim()) {
      error('验证失败', '请输入描述信息');
      return;
    }
    if (financialForm.amount <= 0) {
      error('验证失败', '金额必须大于0');
      return;
    }
    if (!financialForm.date) {
      error('验证失败', '请选择日期');
      return;
    }

    setCreateLoading(true);
    try {
      const newFinancial = await mockApi.createFinancial({
        ...financialForm,
        status: 'completed'
      });

      // 更新本地数据
      setFinancials(prev => [newFinancial, ...prev]);
      setTotalFinancials(prev => prev + 1);

      // 重置表单
      setFinancialForm({
        type: 'income',
        category: '',
        amount: 0,
        description: '',
        date: new Date().toISOString().split('T')[0],
        paymentMethod: '现金',
        orderId: '',
        vehicleId: '',
        invoiceNumber: ''
      });

      setShowCreateModal(false);
      success('创建成功', `${financialForm.type === 'income' ? '收入' : '支出'}记录已成功创建`);
    } catch (err) {
      console.error('Failed to create financial record:', err);
      error('创建失败', '创建财务记录时发生错误，请重试');
    } finally {
      setCreateLoading(false);
    }
  };

  // 处理导出报表
  const handleExportReport = async () => {
    setExportLoading(true);
    info('开始导出', '正在生成财务报表，请稍候...');

    try {
      // 模拟导出过程
      await new Promise(resolve => setTimeout(resolve, 2000));

      // 生成CSV数据
      const csvData = generateCSVData();
      
      // 创建并下载文件
      downloadCSV(csvData, `财务报表_${dateRange.start}_${dateRange.end}.csv`);
      
      success('导出成功', '财务报表已成功导出到您的下载文件夹');
    } catch (err) {
      console.error('Export failed:', err);
      error('导出失败', '导出财务报表时发生错误，请重试');
    } finally {
      setExportLoading(false);
    }
  };

  // 生成CSV数据
  const generateCSVData = () => {
    const headers = ['日期', '类型', '分类', '金额', '描述', '支付方式', '状态', '发票号'];
    const rows = filteredFinancials.map(financial => [
      new Date(financial.date).toLocaleDateString('zh-CN'),
      financial.type === 'income' ? '收入' : '支出',
      financial.category,
      financial.amount,
      financial.description,
      financial.paymentMethod || '未知',
      financial.status === 'completed' ? '已完成' : 
      financial.status === 'pending' ? '待处理' : '已取消',
      financial.invoiceNumber || ''
    ]);

    // 添加统计信息
    const statsRows = [
      [''],
      ['统计信息'],
      ['总收入', '', '', totalIncome, '', '', '', ''],
      ['总支出', '', '', totalExpense, '', '', '', ''],
      ['净利润', '', '', profit, '', '', '', ''],
      ['利润率', '', '', `${profitMargin}%`, '', '', '', ''],
      ['筛选日期范围', '', '', `${dateRange.start} 至 ${dateRange.end}`, '', '', '', '']
    ];

    return [headers, ...rows, ...statsRows];
  };

  // 下载CSV文件
  const downloadCSV = (data: any[][], filename: string) => {
    const csvContent = data.map(row => 
      row.map(field => `"${field}"`).join(',')
    ).join('\n');

    const BOM = '\uFEFF'; // 添加BOM以支持中文
    const blob = new Blob([BOM + csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    
    if (link.download !== undefined) {
      const url = URL.createObjectURL(blob);
      link.setAttribute('href', url);
      link.setAttribute('download', filename);
      link.style.visibility = 'hidden';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
  };

  return (
    <div className="space-y-6 animate-slide-up">
      {/* Toast 通知容器 */}
      <ToastContainer toasts={toasts} onClose={removeToast} />

      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-gray-800">财务管理</h1>
          <p className="text-gray-600">管理运输业务的收入支出和财务分析</p>
        </div>
        <div className="flex space-x-2">
          <Button 
            variant="outline" 
            icon={<Download className="w-4 h-4" />}
            onClick={handleExportReport}
            loading={exportLoading}
          >
            导出报表
          </Button>
          <Button 
            icon={<Plus className="w-4 h-4" />}
            onClick={() => setShowCreateModal(true)}
          >
            记录财务
          </Button>
        </div>
      </div>

      {/* Financial Overview Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <Card hover gradient className="relative overflow-hidden">
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-600 mb-1">总收入</p>
                <p className="text-2xl font-bold text-success-600">¥{(totalIncome / 10000).toFixed(1)}万</p>
                <div className="flex items-center mt-2">
                  <TrendingUp className="w-4 h-4 text-success-500 mr-1" />
                  <span className="text-sm text-success-600">+15.2%</span>
                </div>
              </div>
              <div className="w-12 h-12 bg-gradient-to-br from-success-500 to-success-600 rounded-xl flex items-center justify-center">
                <TrendingUp className="w-6 h-6 text-white" />
              </div>
            </div>
            <div className="absolute top-0 right-0 w-20 h-20 bg-success-100 rounded-full -mr-10 -mt-10 opacity-20"></div>
          </CardContent>
        </Card>

        <Card hover gradient className="relative overflow-hidden">
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-600 mb-1">总支出</p>
                <p className="text-2xl font-bold text-error-600">¥{(totalExpense / 10000).toFixed(1)}万</p>
                <div className="flex items-center mt-2">
                  <TrendingDown className="w-4 h-4 text-error-500 mr-1" />
                  <span className="text-sm text-error-600">+8.7%</span>
                </div>
              </div>
              <div className="w-12 h-12 bg-gradient-to-br from-error-500 to-error-600 rounded-xl flex items-center justify-center">
                <TrendingDown className="w-6 h-6 text-white" />
              </div>
            </div>
            <div className="absolute top-0 right-0 w-20 h-20 bg-error-100 rounded-full -mr-10 -mt-10 opacity-20"></div>
          </CardContent>
        </Card>

        <Card hover gradient className="relative overflow-hidden">
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-600 mb-1">净利润</p>
                <p className={`text-2xl font-bold ${profit >= 0 ? 'text-success-600' : 'text-error-600'}`}>
                  ¥{(profit / 10000).toFixed(1)}万
                </p>
                <div className="flex items-center mt-2">
                  <span className="text-sm text-gray-600">利润率 {profitMargin}%</span>
                </div>
              </div>
              <div className="w-12 h-12 bg-gradient-to-br from-primary-500 to-primary-600 rounded-xl flex items-center justify-center">
                <DollarSign className="w-6 h-6 text-white" />
              </div>
            </div>
            <div className="absolute top-0 right-0 w-20 h-20 bg-primary-100 rounded-full -mr-10 -mt-10 opacity-20"></div>
          </CardContent>
        </Card>

        <Card hover gradient className="relative overflow-hidden">
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-600 mb-1">平均订单价值</p>
                <p className="text-2xl font-bold text-secondary-600">¥{Math.round(totalIncome / 50)}</p>
                <div className="flex items-center mt-2">
                  <span className="text-sm text-gray-600">本月平均</span>
                </div>
              </div>
              <div className="w-12 h-12 bg-gradient-to-br from-secondary-500 to-secondary-600 rounded-xl flex items-center justify-center">
                <FileText className="w-6 h-6 text-white" />
              </div>
            </div>
            <div className="absolute top-0 right-0 w-20 h-20 bg-secondary-100 rounded-full -mr-10 -mt-10 opacity-20"></div>
          </CardContent>
        </Card>
      </div>

      {/* Charts Section */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Income vs Expense Trend */}
        <Card>
          <CardHeader>
            <div className="flex items-center justify-between">
              <h3 className="text-lg font-semibold text-gray-800">收支趋势</h3>
              <Badge variant="info">近6个月</Badge>
            </div>
          </CardHeader>
          <CardContent>
            <ResponsiveContainer width="100%" height={300}>
              <BarChart data={mockFinanceChartData}>
                <CartesianGrid strokeDasharray="3 3" stroke="#f1f5f9" />
                <XAxis dataKey="month" stroke="#64748b" />
                <YAxis stroke="#64748b" />
                <Tooltip 
                  contentStyle={{ 
                    backgroundColor: 'white',
                    border: 'none',
                    borderRadius: '12px',
                    boxShadow: '0 10px 40px rgba(0,0,0,0.1)'
                  }}
                  formatter={(value: any, name: string) => [
                    `¥${(value / 10000).toFixed(1)}万`, 
                    name === 'income' ? '收入' : '支出'
                  ]}
                />
                <Bar dataKey="income" fill="#22c55e" radius={[4, 4, 0, 0]} />
                <Bar dataKey="expense" fill="#ef4444" radius={[4, 4, 0, 0]} />
              </BarChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>

        {/* Expense Categories */}
        <Card>
          <CardHeader>
            <div className="flex items-center justify-between">
              <h3 className="text-lg font-semibold text-gray-800">支出分类</h3>
              <Badge variant="info">本月</Badge>
            </div>
          </CardHeader>
          <CardContent>
            <div className="flex items-center">
              <ResponsiveContainer width="60%" height={250}>
                <RechartsPieChart>
                  <Pie
                    data={expenseCategories}
                    cx="50%"
                    cy="50%"
                    innerRadius={60}
                    outerRadius={100}
                    paddingAngle={5}
                    dataKey="value"
                  >
                    {expenseCategories.map((entry, index) => (
                      <Cell key={`cell-${index}`} fill={entry.color} />
                    ))}
                  </Pie>
                  <Tooltip formatter={(value: any) => [`${value}%`, '占比']} />
                </RechartsPieChart>
              </ResponsiveContainer>
              <div className="w-40% pl-6 space-y-3">
                {expenseCategories.map((item, index) => (
                  <div key={index} className="flex items-center justify-between">
                    <div className="flex items-center space-x-2">
                      <div 
                        className="w-3 h-3 rounded-full" 
                        style={{ backgroundColor: item.color }}
                      />
                      <span className="text-sm text-gray-600">{item.name}</span>
                    </div>
                    <span className="text-sm font-medium text-gray-800">{item.value}%</span>
                  </div>
                ))}
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Filters */}
      <Card>
        <CardContent className="p-6">
          <div className="space-y-4">
            {/* 第一行：搜索和基础筛选 */}
            <div className="flex flex-col lg:flex-row gap-4">
              <div className="flex-1 relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
                <input
                  type="text"
                  placeholder="搜索描述、分类..."
                  className="w-full pl-10 pr-4 py-2.5 border border-gray-300 rounded-xl focus:ring-2 focus:ring-primary-500 focus:border-transparent transition-all duration-200"
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                />
              </div>
              <div className="flex gap-2">
                <select
                  className="px-4 py-2.5 border border-gray-300 rounded-xl focus:ring-2 focus:ring-primary-500 focus:border-transparent transition-all duration-200"
                  value={typeFilter}
                  onChange={(e) => setTypeFilter(e.target.value)}
                >
                  <option value="">全部类型</option>
                  <option value="income">收入</option>
                  <option value="expense">支出</option>
                </select>
                <Button 
                  variant="outline" 
                  icon={<Filter className="w-4 h-4" />}
                  onClick={() => setShowAdvancedFilter(true)}
                  className="relative"
                >
                  更多筛选
                  {activeFiltersCount > 0 && (
                    <span className="absolute -top-2 -right-2 w-5 h-5 bg-primary-500 text-white text-xs rounded-full flex items-center justify-center">
                      {activeFiltersCount}
                    </span>
                  )}
                </Button>
                {/* 重置筛选按钮 */}
                {(activeFiltersCount > 0 || typeFilter || searchTerm || 
                  dateRange.start !== new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0] ||
                  dateRange.end !== new Date().toISOString().split('T')[0]) && (
                  <Button 
                    variant="ghost" 
                    icon={<RotateCcw className="w-4 h-4" />}
                    onClick={resetFilters}
                    className="text-gray-600 hover:text-gray-800"
                  >
                    重置筛选
                  </Button>
                )}
              </div>
            </div>

            {/* 第二行：日期选择 */}
            <div className="flex flex-col sm:flex-row gap-4 items-center">
              <div className="flex items-center space-x-2">
                <Calendar className="w-5 h-5 text-gray-500" />
                <span className="text-sm font-medium text-gray-700">选择日期:</span>
              </div>
              <div className="flex items-center space-x-2">
                <input
                  type="date"
                  className="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                  value={dateRange.start}
                  onChange={(e) => handleDateRangeChange('start', e.target.value)}
                />
                <span className="text-gray-500">至</span>
                <input
                  type="date"
                  className="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                  value={dateRange.end}
                  onChange={(e) => handleDateRangeChange('end', e.target.value)}
                />
              </div>
              <div className="flex gap-2">
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => {
                    const today = new Date().toISOString().split('T')[0];
                    const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
                    handleDateRangeChange('start', sevenDaysAgo);
                    handleDateRangeChange('end', today);
                  }}
                >
                  最近7天
                </Button>
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => {
                    const today = new Date().toISOString().split('T')[0];
                    const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
                    handleDateRangeChange('start', thirtyDaysAgo);
                    handleDateRangeChange('end', today);
                  }}
                >
                  最近30天
                </Button>
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => {
                    const today = new Date().toISOString().split('T')[0];
                    const ninetyDaysAgo = new Date(Date.now() - 90 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
                    handleDateRangeChange('start', ninetyDaysAgo);
                    handleDateRangeChange('end', today);
                  }}
                >
                  最近90天
                </Button>
              </div>
            </div>

            {/* 活跃筛选器显示 */}
            {(activeFiltersCount > 0 || dateRange.start || dateRange.end) && (
              <div className="flex flex-wrap gap-2 pt-2 border-t border-gray-100">
                <span className="text-sm text-gray-600">已应用筛选:</span>
                {dateRange.start && dateRange.end && (
                  <Badge variant="primary" size="sm">
                    日期: {dateRange.start} 至 {dateRange.end}
                  </Badge>
                )}
                {typeFilter && (
                  <Badge variant="info" size="sm">
                    类型: {typeFilter === 'income' ? '收入' : '支出'}
                  </Badge>
                )}
                {searchTerm && (
                  <Badge variant="secondary" size="sm">
                    搜索: {searchTerm}
                  </Badge>
                )}
                {advancedFilters.amountRange.min && (
                  <Badge variant="success" size="sm">
                    最低金额: ¥{advancedFilters.amountRange.min}
                  </Badge>
                )}
                {advancedFilters.amountRange.max && (
                  <Badge variant="success" size="sm">
                    最高金额: ¥{advancedFilters.amountRange.max}
                  </Badge>
                )}
                {advancedFilters.categories.map(category => (
                  <Badge key={category} variant="secondary" size="sm">
                    {category}
                  </Badge>
                ))}
                {advancedFilters.paymentMethods.map(method => (
                  <Badge key={method} variant="warning" size="sm">
                    {method}
                  </Badge>
                ))}
                {advancedFilters.status && (
                  <Badge variant="info" size="sm">
                    {statusOptions.find(s => s.value === advancedFilters.status)?.label}
                  </Badge>
                )}
              </div>
            )}
          </div>
        </CardContent>
      </Card>

      {/* Financial Records */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <h2 className="text-lg font-semibold text-gray-800">财务记录</h2>
            <Badge variant="info">{filteredFinancials.length} 条记录</Badge>
          </div>
        </CardHeader>
        <CardContent className="p-0">
          {loading ? (
            <div className="p-6">
              <div className="space-y-4">
                {Array.from({ length: 5 }).map((_, i) => (
                  <div key={i} className="flex items-center space-x-4 animate-pulse">
                    <div className="w-12 h-12 bg-gray-200 rounded-xl"></div>
                    <div className="flex-1 space-y-2">
                      <div className="h-4 bg-gray-200 rounded w-1/4"></div>
                      <div className="h-3 bg-gray-200 rounded w-1/2"></div>
                    </div>
                    <div className="h-6 bg-gray-200 rounded w-16"></div>
                  </div>
                ))}
              </div>
            </div>
          ) : (
            <>
              <div className="divide-y divide-gray-100">
                {filteredFinancials.map((financial) => (
                  <div key={financial.id} className="p-6 hover:bg-gray-50 transition-colors duration-200">
                    <div className="flex items-center justify-between">
                      <div className="flex items-center space-x-4">
                        <div className={`w-12 h-12 rounded-xl flex items-center justify-center ${
                          financial.type === 'income' 
                            ? 'bg-gradient-to-br from-success-100 to-success-200' 
                            : 'bg-gradient-to-br from-error-100 to-error-200'
                        }`}>
                          {financial.type === 'income' ? (
                            <TrendingUp className="w-6 h-6 text-success-600" />
                          ) : (
                            <TrendingDown className="w-6 h-6 text-error-600" />
                          )}
                        </div>
                        <div>
                          <div className="flex items-center space-x-2 mb-1">
                            <h3 className="font-semibold text-gray-800">{financial.category}</h3>
                            <Badge 
                              variant={financial.type === 'income' ? 'success' : 'error'} 
                              size="sm"
                            >
                              {financial.type === 'income' ? '收入' : '支出'}
                            </Badge>
                            {/* 支付方式标签 */}
                            {financial.paymentMethod && (
                              <div className={`inline-flex items-center space-x-1 px-2 py-1 rounded-full text-xs font-medium ${getPaymentMethodColor(financial.paymentMethod)}`}>
                                {getPaymentMethodIcon(financial.paymentMethod)}
                                <span>{financial.paymentMethod}</span>
                              </div>
                            )}
                          </div>
                          <div className="flex items-center space-x-4 text-sm text-gray-600">
                            <span>{financial.description}</span>
                            <div className="flex items-center space-x-1">
                              <Calendar className="w-4 h-4" />
                              <span>{new Date(financial.date).toLocaleDateString('zh-CN')}</span>
                            </div>
                            {financial.invoiceNumber && (
                              <div className="flex items-center space-x-1">
                                <Receipt className="w-4 h-4" />
                                <span>{financial.invoiceNumber}</span>
                              </div>
                            )}
                          </div>
                        </div>
                      </div>
                      <div className="text-right">
                        <p className={`text-lg font-bold ${
                          financial.type === 'income' ? 'text-success-600' : 'text-error-600'
                        }`}>
                          {financial.type === 'income' ? '+' : '-'}¥{financial.amount.toLocaleString()}
                        </p>
                        <Badge 
                          variant={
                            financial.status === 'completed' ? 'success' :
                            financial.status === 'pending' ? 'warning' : 'error'
                          }
                          size="sm"
                        >
                          {financial.status === 'completed' ? '已完成' :
                           financial.status === 'pending' ? '待处理' : '已取消'}
                        </Badge>
                      </div>
                    </div>
                  </div>
                ))}
              </div>

              {/* Pagination */}
              <Pagination
                currentPage={currentPage}
                totalPages={totalPages}
                totalItems={totalFinancials}
                onPageChange={setCurrentPage}
                className="p-6 border-t border-gray-100"
              />
            </>
          )}
        </CardContent>
      </Card>

      {/* Advanced Filter Modal */}
      <Modal
        isOpen={showAdvancedFilter}
        onClose={() => setShowAdvancedFilter(false)}
        title="高级筛选"
        size="lg"
      >
        <div className="space-y-6">
          {/* 金额范围 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-3">金额范围 (元)</label>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-xs text-gray-500 mb-1">最小金额</label>
                <input
                  type="number"
                  placeholder="0"
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                  value={advancedFilters.amountRange.min}
                  onChange={(e) => handleAdvancedFilterChange('amountRange', {
                    ...advancedFilters.amountRange,
                    min: e.target.value
                  })}
                />
              </div>
              <div>
                <label className="block text-xs text-gray-500 mb-1">最大金额</label>
                <input
                  type="number"
                  placeholder="无限制"
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                  value={advancedFilters.amountRange.max}
                  onChange={(e) => handleAdvancedFilterChange('amountRange', {
                    ...advancedFilters.amountRange,
                    max: e.target.value
                  })}
                />
              </div>
            </div>
          </div>

          {/* 交易分类 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-3">交易分类</label>
            <div className="grid grid-cols-3 md:grid-cols-4 gap-2">
              {[...incomeCategories, ...expenseCategories_list].map(category => (
                <label key={category} className="flex items-center space-x-2 cursor-pointer">
                  <input
                    type="checkbox"
                    checked={advancedFilters.categories.includes(category)}
                    onChange={() => handleCategoryToggle(category)}
                    className="rounded border-gray-300 text-primary-600 focus:ring-primary-500"
                  />
                  <span className="text-sm text-gray-700">{category}</span>
                </label>
              ))}
            </div>
          </div>

          {/* 支付方式 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-3">支付方式</label>
            <div className="grid grid-cols-3 md:grid-cols-4 gap-2">
              {paymentMethods.map(method => (
                <label key={method} className="flex items-center space-x-2 cursor-pointer">
                  <input
                    type="checkbox"
                    checked={advancedFilters.paymentMethods.includes(method)}
                    onChange={() => handlePaymentMethodToggle(method)}
                    className="rounded border-gray-300 text-primary-600 focus:ring-primary-500"
                  />
                  <div className="flex items-center space-x-1">
                    {getPaymentMethodIcon(method)}
                    <span className="text-sm text-gray-700">{method}</span>
                  </div>
                </label>
              ))}
            </div>
          </div>

          {/* 状态筛选 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-3">交易状态</label>
            <select
              className="w-full md:w-auto px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
              value={advancedFilters.status}
              onChange={(e) => handleAdvancedFilterChange('status', e.target.value)}
            >
              <option value="">全部状态</option>
              {statusOptions.map(option => (
                <option key={option.value} value={option.value}>{option.label}</option>
              ))}
            </select>
          </div>

          {/* 筛选操作按钮 */}
          <div className="flex justify-between pt-4 border-t border-gray-200">
            <Button
              variant="outline"
              icon={<RotateCcw className="w-4 h-4" />}
              onClick={resetFilters}
            >
              重置筛选
            </Button>
            <div className="flex space-x-3">
              <Button
                variant="outline"
                onClick={() => setShowAdvancedFilter(false)}
              >
                取消
              </Button>
              <Button
                icon={<Filter className="w-4 h-4" />}
                onClick={applyFilters}
              >
                应用筛选 ({activeFiltersCount})
              </Button>
            </div>
          </div>
        </div>
      </Modal>

      {/* Create Financial Record Modal */}
      <Modal
        isOpen={showCreateModal}
        onClose={() => setShowCreateModal(false)}
        title="记录财务"
        size="lg"
      >
        <div className="space-y-6">
          {/* 类型选择 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-3">财务类型</label>
            <div className="grid grid-cols-2 gap-4">
              <button
                type="button"
                onClick={() => setFinancialForm(prev => ({ ...prev, type: 'income', category: '' }))}
                className={`p-4 rounded-xl border-2 transition-all duration-200 ${
                  financialForm.type === 'income'
                    ? 'border-success-500 bg-success-50 text-success-700'
                    : 'border-gray-200 hover:border-gray-300'
                }`}
              >
                <div className="flex items-center space-x-3">
                  <div className={`w-10 h-10 rounded-lg flex items-center justify-center ${
                    financialForm.type === 'income' ? 'bg-success-500' : 'bg-gray-400'
                  }`}>
                    <TrendingUp className="w-5 h-5 text-white" />
                  </div>
                  <div className="text-left">
                    <p className="font-medium">收入</p>
                    <p className="text-sm text-gray-500">记录收入项目</p>
                  </div>
                </div>
              </button>

              <button
                type="button"
                onClick={() => setFinancialForm(prev => ({ ...prev, type: 'expense', category: '' }))}
                className={`p-4 rounded-xl border-2 transition-all duration-200 ${
                  financialForm.type === 'expense'
                    ? 'border-error-500 bg-error-50 text-error-700'
                    : 'border-gray-200 hover:border-gray-300'
                }`}
              >
                <div className="flex items-center space-x-3">
                  <div className={`w-10 h-10 rounded-lg flex items-center justify-center ${
                    financialForm.type === 'expense' ? 'bg-error-500' : 'bg-gray-400'
                  }`}>
                    <TrendingDown className="w-5 h-5 text-white" />
                  </div>
                  <div className="text-left">
                    <p className="font-medium">支出</p>
                    <p className="text-sm text-gray-500">记录支出项目</p>
                  </div>
                </div>
              </button>
            </div>
          </div>

          {/* 基本信息 */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">分类 *</label>
              <select
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                value={financialForm.category}
                onChange={(e) => setFinancialForm(prev => ({ ...prev, category: e.target.value }))}
                required
              >
                <option value="">请选择分类</option>
                {(financialForm.type === 'income' ? incomeCategories : expenseCategories_list).map(category => (
                  <option key={category} value={category}>{category}</option>
                ))}
              </select>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">金额 (元) *</label>
              <input
                type="number"
                min="0"
                step="0.01"
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                value={financialForm.amount || ''}
                onChange={(e) => setFinancialForm(prev => ({ ...prev, amount: Number(e.target.value) }))}
                placeholder="请输入金额"
                required
              />
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">描述 *</label>
            <textarea
              rows={3}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
              value={financialForm.description}
              onChange={(e) => setFinancialForm(prev => ({ ...prev, description: e.target.value }))}
              placeholder="请输入详细描述"
              required
            />
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">日期 *</label>
              <input
                type="date"
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                value={financialForm.date}
                onChange={(e) => setFinancialForm(prev => ({ ...prev, date: e.target.value }))}
                required
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">支付方式 *</label>
              <select
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                value={financialForm.paymentMethod}
                onChange={(e) => setFinancialForm(prev => ({ ...prev, paymentMethod: e.target.value }))}
                required
              >
                {paymentMethods.map(method => (
                  <option key={method} value={method}>{method}</option>
                ))}
              </select>
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">发票号</label>
            <input
              type="text"
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
              value={financialForm.invoiceNumber}
              onChange={(e) => setFinancialForm(prev => ({ ...prev, invoiceNumber: e.target.value }))}
              placeholder="请输入发票号（可选）"
            />
          </div>

          {/* 关联信息 */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">关联订单</label>
              <input
                type="text"
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                value={financialForm.orderId}
                onChange={(e) => setFinancialForm(prev => ({ ...prev, orderId: e.target.value }))}
                placeholder="请输入订单号（可选）"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">关联车辆</label>
              <input
                type="text"
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                value={financialForm.vehicleId}
                onChange={(e) => setFinancialForm(prev => ({ ...prev, vehicleId: e.target.value }))}
                placeholder="请输入车牌号（可选）"
              />
            </div>
          </div>

          {/* 操作按钮 */}
          <div className="flex justify-end space-x-3 pt-4 border-t border-gray-200">
            <Button
              variant="outline"
              onClick={() => setShowCreateModal(false)}
              disabled={createLoading}
            >
              取消
            </Button>
            <Button
              icon={<Save className="w-4 h-4" />}
              onClick={handleCreateFinancial}
              loading={createLoading}
            >
              保存记录
            </Button>
          </div>
        </div>
      </Modal>
    </div>
  );
};